import React from 'react'

import styles from './index.module.css'
import NavHeader from '../../components/NavHeader'
import {API} from '../../utils/api'
import {Link} from 'react-router-dom'
import { Toast } from 'antd-mobile'

const BMap = window.BMap

export default class Map extends React.Component {
  state = {
    houseList: []
  }

  componentDidMount() {
    this.initMap()
  }

  initMap = () => {
    const {label: cityName, value: cityId} = JSON.parse(localStorage.getItem('hkzf_city') || '{}')

    const map = new BMap.Map("container")
    this.map = map
    var myGeo = new BMap.Geocoder()  
    myGeo.getPoint(cityName || '上海' , async point => {      
      if (point) {      
        map.centerAndZoom(point, 11) 
        cityId && this.renderOverlays(cityId)
      }      
    }, 
    cityName || '上海')

    map.addControl(new BMap.NavigationControl())   
    map.addControl(new BMap.ScaleControl())

    map.addEventListener('movestart', () => {
      this.setState({
        houseList: []
      })
    })
  }

  renderOverlays = async cityCode => {
    Toast.loading('加载中...', 0)

    const {data: {body: areaList}} = await API.get(`/area/map?id=${cityCode}`)

    Toast.hide()

    const {type, nextZoom} = this.getTypeAndZoom()

    areaList.forEach(item => {
      this.createOverlays(item, type, nextZoom)
    })
  }

  getTypeAndZoom = () => {
    const zoom = this.map.getZoom()
    let type, nextZoom
    if(zoom >= 10 && zoom < 12) {
      type = 'circle'
      nextZoom = 13
    } else if(zoom >= 12 && zoom < 14) {
      type = 'circle'
      nextZoom = 15
    } else if(zoom >= 14) {
      type = 'rect'
    }

    return {
      type,
      nextZoom
    }
  }

  createOverlays = (item, type, nextZoom) => {
    const {label: areaName, value: areaCode, coord: {latitude, longitude}, count} = item

    if(type === 'circle') {
      this.createCircle(areaName, areaCode, latitude, longitude, count, nextZoom)
    } else {
      this.createRect(areaName, areaCode, latitude, longitude, count)
    }
  }

  createCircle = (areaName, areaCode, latitude, longitude, count, zoom) => {
    const position = new BMap.Point(longitude, latitude)
    const opts = {
      position, 
      offset: new BMap.Size(-35, -35)  
    }
    const label = new BMap.Label(null, opts)
    label.setContent(`
      <div class="${styles.cityItem}">
        <div class=${styles.title}>${areaName}</div>
        <div class=${styles.count}>${count}套</div>
      </div>
    `)
    label.addEventListener('click', () => {
      this.renderOverlays(areaCode)
      this.map.centerAndZoom(position, zoom) 
      setTimeout(()=> this.map.clearOverlays())
    })
    label.setStyle({
      border: 0,
      borderRadius: '50%'
    })
    this.map.addOverlay(label)
  }

  createRect = (areaName, areaCode, latitude, longitude, count) => {
    const position = new BMap.Point(longitude, latitude)
    const opts = {
      position, 
      offset: new BMap.Size(-50, -28)  
    }
    const label = new BMap.Label(null, opts)
    label.setContent(`
      <div class="${styles.rect}">
        <span class="${styles.housename}">${areaName}</span>
        <span class="${styles.housenum}">${count}套</span>
        <i class="${styles.arrow}"></i>
      </div>
    `)
    label.addEventListener('click', ({changedTouches}) => {
      this.getHouseList(areaCode)

      const x = window.innerWidth / 2 - changedTouches[0].clientX
      const y = (window.innerHeight - 330) / 2 - changedTouches[0].clientY

      this.map.panBy(x, y)
    })
    label.setStyle({
      border: 0,
      borderRadius: '50%'
    })
    this.map.addOverlay(label)
  }

  getHouseList = async code => {
    Toast.loading('加载中...', 0)
    const {data: {body: {list}}} = await API.get(`/houses?cityId=${code}`)
    Toast.hide()

    this.setState({
      houseList: list
    })
  }

  renderHouseList = () => {
    return (
      <div
        className={[
          styles.houseList,
          this.state.houseList.length > 0 ? styles.show : ''
        ].join(' ')}
      >
        <div className={styles.titleWrap}>
          <h1 className={styles.listTitle}>房屋列表</h1>
          <Link className={styles.titleMore} to="/home/list">
            更多房源
          </Link>
        </div>
        <div className={styles.houseItems}>
          {this.state.houseList.map(item => (
            <div className={styles.house} key={item.houseCode}>
              <div className={styles.imgWrap}>
                <img
                  className={styles.img}
                  src={`http://localhost:8080${item.houseImg}`}
                  alt=""
                />
              </div>
              <div className={styles.content}>
                <h3 className={styles.title}>{item.title}</h3>
                <div className={styles.desc}>{item.desc}</div>
                <div>
                  {item.tags.map((tag, index) => {
                    const tagClass = 'tag' + (index + 1)
                    return (
                      <span
                        className={[styles.tag, styles[tagClass]].join(' ')}
                        key={tag}
                      >
                        {tag}
                      </span>
                    )
                  })}
                </div>
                <div className={styles.price}>
                  <span className={styles.priceNum}>{item.price}</span> 元/月
                </div>
              </div>
            </div>
          ))}
        </div>
      </div>
    )
  }

  render() {
    return (
      <div className={styles['map-box']}>
        <NavHeader>地图找房</NavHeader>

        <div id="container"></div>

        {this.renderHouseList()}
      </div>
    )
  }
}